﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json.Linq;

namespace weixin.api
{
    public class WXComponent
    {
        /// <summary>
        /// 获取第三方平台component_access_token
        /// </summary>
        /// <param name="expires_last_key"></param>
        /// <param name="component_access_token_key"></param>
        public static string GetComponentAccessToken(string sAppid)
        {
            string component_access_token = System.Web.HttpRuntime.Cache["component_access_token"] + "";
            if (string.IsNullOrEmpty(component_access_token))
            {
                string jsonstr = GetComponentAccessTokenFromFile(sAppid);
                if (!string.IsNullOrEmpty(jsonstr))
                {
                    JObject json = JObject.Parse(jsonstr);
                    if (DateTime.Parse(json.GetValue("expires_date").ToString()) <= DateTime.Now)
                    {
                        jsonstr = GetComponentAccessTokenFromNet(sAppid);
                    }
                }
                else
                {
                    jsonstr = GetComponentAccessTokenFromNet(sAppid);
                }
                JObject newjson = JObject.Parse(jsonstr);
                component_access_token = newjson.GetValue("component_access_token").ToString();
                HttpRuntime.Cache.Insert("component_access_token", component_access_token, null, DateTime.Parse(newjson.GetValue("expires_date").ToString()), System.Web.Caching.Cache.NoSlidingExpiration);
                return component_access_token;
            }
            else
            {
                return component_access_token;
            }
        }

        public static string GetComponentAccessTokenFromFile(string sAppID)
        {
            string filepath = HttpContext.Current.Server.MapPath("/Cache/" + sAppID);
            if (!System.IO.File.Exists(filepath))
            {
                return string.Empty;
            }
            string fileContent = System.IO.File.ReadAllText(filepath);
            return fileContent;
        }

        public static string GetComponentAccessTokenFromNet(string sAppid)
        {
            string filepath = HttpContext.Current.Server.MapPath("/Cache/ComponentVerifyTicket");
            if (!System.IO.File.Exists(filepath))
            {
                throw new Exception("微信未推送ComponentVerifyTicket,请等待最长10分钟再操作");
            }
            string ComponentVerifyTicket = System.IO.File.ReadAllText(filepath);

            string api = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
            System.Text.StringBuilder postdata = new System.Text.StringBuilder();
            postdata.Append("{");
            postdata.AppendFormat("\"component_appid\":\"{0}\" ,", sAppid);
            postdata.AppendFormat("\"component_appsecret\": \"{0}\", ", WXConfig.sAppSecret);
            postdata.AppendFormat("\"component_verify_ticket\": \"{0}\" ", ComponentVerifyTicket);
            postdata.Append("}");
            //WriteLog(postdata.ToString());
            string jsonstr = WXComm.GetHtmlResponse(api, "POST", postdata.ToString());
            JObject json = JObject.Parse(jsonstr);
            json.Add("expires_date", DateTime.Now.AddSeconds(int.Parse(json.GetValue("expires_in").ToString()) - 100));
            jsonstr = Newtonsoft.Json.JsonConvert.SerializeObject(json);
            WXComm.WriteLog(jsonstr.ToString());
            string accfapth = HttpContext.Current.Server.MapPath("/Cache/" + sAppid);
            System.IO.FileStream fs = new System.IO.FileStream(accfapth, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite);
            fs.Write(System.Text.Encoding.UTF8.GetBytes(jsonstr), 0, System.Text.Encoding.UTF8.GetByteCount(jsonstr));
            fs.Flush();
            fs.Close();
            fs.Dispose();
            return jsonstr;
        }

        /// <summary>
        /// 获取预授权码pre_auth_code
        /// </summary>
        public static void GetPreAuthCode()
        {
            string api = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=" + GetComponentAccessToken(WXConfig.sAppID);
            System.Text.StringBuilder postdata = new System.Text.StringBuilder();
            postdata.Append("{");
            postdata.AppendFormat("\"component_appid\":\"{0}\" ", WXConfig.sAppID);
            postdata.Append("}");
            string jsonstr = WXComm.GetHtmlResponse(api, "POST", postdata.ToString());
            WXComm.WriteLog(jsonstr.ToString());

            DeserializeJson dic = new DeserializeJson().GetResult(jsonstr);
            string pre_auth_code = dic.GetString("pre_auth_code");
            if (!string.IsNullOrEmpty(pre_auth_code))
            {
                System.Web.HttpRuntime.Cache.Insert("pre_auth_code_expires", DateTime.Now, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10));
                System.Web.HttpRuntime.Cache.Insert("pre_auth_code", pre_auth_code, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(20));
            }
            else
            {
                WXComm.WriteLog(jsonstr);
            }
        }

        /// <summary>
        /// 使用授权码换取公众号的接口调用凭据和授权信息
        /// </summary>
        public static void GetAuthorizationInfo()
        {
            if (System.Web.HttpRuntime.Cache["pre_auth_code_expires"] == null)
            {
                GetPreAuthCode();
            }
            string api = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" + System.Web.HttpRuntime.Cache["component_access_token"];
            System.Text.StringBuilder postdata = new System.Text.StringBuilder();
            postdata.Append("{");
            postdata.AppendFormat("\"component_appid\":\"{0}\" ,", WXConfig.sAppID);
            postdata.AppendFormat("\"authorization_code\":\"{0}\" ", System.Web.HttpRuntime.Cache["pre_auth_code"]);
            postdata.Append("}");
            string jsonstr = WXComm.GetHtmlResponse(api, "POST", postdata.ToString());
            WXComm.WriteLog(jsonstr.ToString());

            DeserializeJson dic = new DeserializeJson().GetResult(jsonstr);
            string authorization_info = dic.GetString("authorization_info.authorizer_appid");
            if (!string.IsNullOrEmpty(authorization_info))
            {
                System.Web.HttpRuntime.Cache.Insert("authorization_info_expires", DateTime.Now, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(100));
                System.Web.HttpRuntime.Cache.Insert("authorization_info", dic, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(120));

                //{
                //    "authorization_info": {
                //        "authorizer_appid": "wxf8b4f85f3a794e77",
                //        "authorizer_access_token": "QXjUqNqfYVH0yBE1iI_7vuN_9gQbpjfK7hYwJ3P7xOa88a89-Aga5x1NMYJyB8G2yKt1KCl0nPC3W9GJzw0Zzq_dBxc8pxIGUNi_bFes0qM",
                //        "expires_in": 7200,
                //        "authorizer_refresh_token": "dTo-YCXPL4llX-u1W1pPpnp8Hgm4wpJtlR6iV0doKdY",
                //        "func_info": [
                //            {
                //                "funcscope_category": {
                //                    "id": 1
                //                }
                //            },
                //            {
                //                "funcscope_category": {
                //                    "id": 2
                //                }
                //            },
                //            {
                //                "funcscope_category": {
                //                    "id": 3
                //                }
                //            }
                //        ]
                //    }
                //}
            }
            else
            {
                WXComm.WriteLog(jsonstr);
            }
        }

        /// <summary>
        /// 获取（刷新）授权公众号的接口调用凭据（令牌）
        /// </summary>
        public static void GetAuthorizerToken()
        {
            if (System.Web.HttpRuntime.Cache["authorization_info_expires"] == null)
            {
                GetAuthorizationInfo();
            }
            DeserializeJson dicc = (DeserializeJson)System.Web.HttpRuntime.Cache["authorization_info"];

            string api = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=" + System.Web.HttpRuntime.Cache["component_access_token"];
            System.Text.StringBuilder postdata = new System.Text.StringBuilder();
            postdata.Append("{");
            postdata.AppendFormat("\"component_appid\":\"{0}\", ", WXConfig.sAppID);
            postdata.AppendFormat("\"authorizer_appid\":\"{0}\", ", dicc.GetString("authorization_info.authorizer_appid"));
            postdata.AppendFormat("\"authorizer_refresh_token\":\"{0}\" ", dicc.GetString("authorization_info.authorizer_refresh_token"));
            postdata.Append("}");
            string jsonstr = WXComm.GetHtmlResponse(api, "POST", postdata.ToString());
            WXComm.WriteLog(jsonstr.ToString());

            DeserializeJson dic = new DeserializeJson().GetResult(jsonstr);
            string authorizer_access_token = dic.GetString("authorizer_access_token");
            if (!string.IsNullOrEmpty(authorizer_access_token))
            {
                System.Web.HttpRuntime.Cache.Insert("authorizer_access_token_expires", DateTime.Now, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(100));
                System.Web.HttpRuntime.Cache.Insert("authorizer_access_token", authorizer_access_token, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(120));
                //System.Web.HttpRuntime.Cache.Insert("authorizer_refresh_token", dic.GetString("authorizer_refresh_token"), null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(120));
            }
            else
            {
                WXComm.WriteLog(jsonstr);
            }
        }

        /// <summary>
        /// 获取授权方的公众号帐号基本信息
        /// </summary>
        public static void GetAuthorizerAccountInfo()
        {
            if (System.Web.HttpRuntime.Cache["authorization_info_expires"] == null)
            {
                GetAuthorizationInfo();
            }
            DeserializeJson dicc = (DeserializeJson)System.Web.HttpRuntime.Cache["authorization_info"];

            string api = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=" + System.Web.HttpRuntime.Cache["component_access_token"];
            System.Text.StringBuilder postdata = new System.Text.StringBuilder();
            postdata.Append("{");
            postdata.AppendFormat("\"component_appid\":\"{0}\", ", WXConfig.sAppID);
            postdata.AppendFormat("\"authorizer_appid\":\"{0}\" ", dicc.GetString("authorization_info.authorizer_appid"));
            postdata.Append("}");
            string jsonstr = WXComm.GetHtmlResponse(api, "POST", postdata.ToString());
            WXComm.WriteLog(jsonstr.ToString());

            DeserializeJson dic = new DeserializeJson().GetResult(jsonstr);
            string authorizer_info = dic.GetString("authorizer_info");
            if (!string.IsNullOrEmpty(authorizer_info))
            {

            }
            else
            {
                WXComm.WriteLog(jsonstr);
            }
        }
    }
}